import { useMessage } from '@/hook/useMessage';
/**
 * 将传入文件流自动识别类型，转出下载的功能函数
 * @author 莫若省
 * @param data  传入的数据流
 * @param fileName  文件名称
 */
export const fileStreamToDownload = async (
  data: Blob | string | ArrayBuffer | Uint8Array | File,
  fileName?: string,
): Promise<void> => {
  try {
    fileName = fileName || 'new_file';
    let blob: Blob;
    let mimeType = '';

    if (typeof data === 'string') {
      if (data.startsWith('http://') || data.startsWith('https://')) {
        const response = await fetch(data);
        if (!response.ok) throw new Error('从服务器下载文件时发生错误');
        blob = await response.blob();
        mimeType = response.headers.get('Content-Type') || '';
      } else if (data.startsWith('data:')) {
        const [header, base64Data] = data.split(',');
        mimeType = header.split(':')[1].split(';')[0];
        blob = new Blob(
          [Uint8Array.from(atob(base64Data), (c) => c.charCodeAt(0))],
          { type: mimeType },
        );
      } else {
        throw new Error('不支持的数据格式!');
      }
    } else if (
      data instanceof Blob ||
      data instanceof ArrayBuffer ||
      data instanceof Uint8Array ||
      (data as any) instanceof File
    ) {
      blob = data instanceof File ? data : new Blob([data]);
      mimeType = blob.type;
    } else {
      throw new Error('不支持的数据格式!');
    }

    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.type = mimeType;
    link.dispatchEvent(new MouseEvent('click'));
    URL.revokeObjectURL(link.href);
    link.remove();
  } catch (error) {
    useMessage({
      type: 'error',
      message: '转换/下载文件时出现错误',
    });
    console.error(error);
  }
};
